import os
import config
import channels_utils
import models

lib_path = os.path.dirname(os.path.realpath(__file__)) + os.path.sep

config = config.Config()

build_tool_path = config.get_lib_info()['build_tools_path']
java_home = config.get_lib_info()['java_home']
sign_info = config.get_sign_info()


def resource_zip(apk_path, ziapk_path) -> bool:
    """对齐资源"""
    zip_common = f"{os.path.join(build_tool_path, 'zipalign')} -f -v 4 {apk_path} {ziapk_path}"
    zipResult = os.system(zip_common)
    if zipResult == 0:
        print("对齐资源成功")
    else:
        print("对齐资源失败")
    return zipResult == 0


def channel_create(apk_path: str) -> str:
    """生成渠道包"""
    path = channels_utils.build_channels(apk_path)
    return path


def sign_app(data, base_dir, apk_path):
    # 生成sign目录
    sign_dir = os.path.join(os.path.dirname(apk_path), "sign")
    if not os.path.exists(sign_dir):
        os.mkdir(sign_dir)
    print("开始加固......")
    for item in data:
        if item.endswith('.apk'):
            file_path = os.path.join(base_dir, item)
            sign = models.SignClass()
            sign.java_home = java_home
            sign.jar_path = build_tool_path
            sign.store_file = sign_info['storeFile']
            sign.store_pass = sign_info['storePassword']
            sign.key_alias = sign_info['keyAlias']
            sign.key_pass = sign_info['keyPassword']
            sign.save_file_path = os.path.join(sign_dir, f"sign-{os.path.basename(file_path)}")
            sign.input_file_path = file_path
            sign.run()
    print("签名完成")
